package com.pulaien.shop.controller;


import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.pulaien.common.core.controller.BaseController;
import com.pulaien.common.core.domain.AjaxResult;
import com.pulaien.common.core.domain.entity.SysDictData;
import com.pulaien.common.core.domain.entity.SysUser;
import com.pulaien.common.core.page.TableDataInfo;
import com.pulaien.common.domain.ResponseCode;
import com.pulaien.common.utils.*;
import com.pulaien.common.utils.date.DateUtils;
import com.pulaien.common.utils.date.EnumDateStyle;
import com.pulaien.common.utils.file.EasyexcelUtil;
import com.pulaien.common.utils.oss.AliOssUploadUtils;
import com.pulaien.common.utils.poi.ExcelUtils;
import com.pulaien.system.domain.*;
import com.pulaien.system.domain.dao.AddressReq;
import com.pulaien.system.domain.dao.OutboundReq;
import com.pulaien.system.domain.dto.*;
import com.pulaien.system.mapper.CustomerBillMapper;
import com.pulaien.system.mapper.OrderDetailMapper;
import com.pulaien.system.mapper.OrderMapper;
import com.pulaien.system.mapper.SysDictDataMapper;
import com.pulaien.system.service.IConfigLogisticsCompanyService;
import com.pulaien.system.service.IExchangeRateService;
import com.pulaien.system.service.IOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商城订单Controller
 *
 * @author pulaien
 * @date 2023-04-06
 */
@Slf4j
@RestController
@RequestMapping("/shop/order")
@Api(tags = "商城端客户订单")
public class ShopOrderController extends BaseController {


    @Resource
    private IOrderService orderService;

    @Resource
    private IExchangeRateService exchangeRateService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private IConfigLogisticsCompanyService configLogisticsCompanyService;

    @Autowired
    private CustomerBillMapper customerBillMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @ApiOperation(value = "导出待支付订单费用")
    @RequestMapping(value = "/exportWaitPayOrder",method = RequestMethod.GET)
    public void exportWaitPayOrder(HttpServletResponse response, OrderQueryParam queryParam){
        //查询导出数据
        WaitPayOrderExcelResult result =  orderService.queryExportData(queryParam);

        WaitPayOrderExcelVO vo = result.getVo();
        List<WaitPayOrderExcelVO> vos = result.getVos();

        EasyexcelUtil.downloadExcel(response,"excelTemplates/WaitPayOrderTemplate.xlsx",
                "ダウンロード",vo,vos);
    }

    @ApiOperation("支付")
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult pay(@RequestBody OrderPayParam orderPayParam) {
        return orderService.pay(orderPayParam);
    }

    /**
     * PayPal 支付成功 回调
     * @param paymentId
     * @param payerId
     */
    @GetMapping("/payPalSuccess")
    public AjaxResult payPalSuccess(@RequestParam("orderGroupNo") String orderGroupNo, @RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId) {
        return orderService.payPalSuccess(orderGroupNo, paymentId, payerId);
    }

    /**
     * paypal 回调 取消支付
     * @throws IOException
     */
    @GetMapping("/payPalCancel")
    public AjaxResult payPalCancel(@RequestParam("orderGroupNo") String orderGroupNo){
        return orderService.payPalCancel(orderGroupNo);
    }


    @ApiOperation("查询商品（新增装箱单）")
    @RequestMapping(value = "/GoodsList", method = RequestMethod.POST)
    @ResponseBody
    public TableDataInfo GoodsList(@RequestBody ExtGoodsListDto goodsListDto) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        goodsListDto.setUserId(currentUser.getUserId());
        return this.orderService.getGoodsList(goodsListDto);
    }

    @ApiOperation("获取订单详情箱子类型、opp袋、物流公司、购买账号、检品选项集合、水洗标模板")
    @RequestMapping(value = "/getOrderInfoConfigList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getOrderInfoConfig() {
        JSONObject orderInfoConfig = this.orderService.getOrderInfoConfig();
        return AjaxResult.success(orderInfoConfig);
    }

    @ApiOperation("页面信息快速保存")
    @RequestMapping(value = "/quickSave", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult quickSave(@RequestBody QuickSaveParam param) {
        return this.orderService.quickSave(param);
    }

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request, OrderQueryParam queryParam)
    {
        if(StringUtils.isNotBlank(queryParam.getOrderNo())) {
            if(queryParam.getOrderNo().contains("-")) {
                queryParam.setOrderShowNo(queryParam.getOrderNo());
            } else {
                queryParam.setId(Long.valueOf(queryParam.getOrderNo()));
            }
        }

        startPage();
        queryParam.setCustomerUserId(SecurityUtils.getUserId());
        List<ExtOrder> list = this.orderService.list(queryParam);
        List<ExtOrder> list_new = new ArrayList<>();

        Date date = new Date();
        Instant now = date.toInstant();

        list.forEach(
                s -> {

                    if(com.pulaien.common.utils.StringUtils.isNotEmpty(s.getGoodsSpecs())) {
                        String[] split = s.getGoodsSpecs().split(";");
                        s.setGoodsSpecsList(Arrays.stream(split).collect(Collectors.toList()));
                        s.setStorageTimeSize(0L);
                        if(null != s.getStorageTimeBegin()) {
                            Instant end = s.getStorageTimeBegin().toInstant();
                            Long day = ChronoUnit.DAYS.between(end, now);
                            if(day >0) {
                                s.setStorageTimeSize(day);
                            }
                        }



                        list_new.add(s);
                    }
                }
        );

        return getDataTable(list_new , new PageInfo(list).getTotal());
    }

    @ApiOperation("查询订单数量")
    @RequestMapping(value = "/orderCount",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult orderCount(OrderQueryParam queryParam){
        queryParam.setCustomerUserId(SecurityUtils.getUserId());
        ExtOrderCount result = orderService.orderCount(queryParam);
        return AjaxResult.success(result);
    }

    @ApiOperation("修改国内运单号信息")
    @RequestMapping(value = "/updateTrackingNumberCn", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult updateTrackNumberCn(@RequestBody OrderInfoUpdateParam orderInfoUpdateParam) {
        return this.orderService.updateTrackingNumberCn(orderInfoUpdateParam);
    }

    @ApiOperation("客户退货")
    @RequestMapping(value = "/rejectByCus/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult rejectByCus(@PathVariable Long id) {
        return this.orderService.rejectForCustomer(SecurityUtils.getLoginUser().getUser(), id);
    }
    @ApiOperation("客户销毁")
    @RequestMapping(value = "/destroyByCus/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult destroyByCus(@PathVariable Long id) {
        return this.orderService.destroyForCustomer(SecurityUtils.getLoginUser().getUser(), id);

    }

    @ApiOperation("仓库保管")
    @RequestMapping(value = "/storeKeeping/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult storeKeeping(@PathVariable Long id) {
        return orderService.storeKeeping(SecurityUtils.getLoginUser().getUser(), id);
    }

    @ApiOperation("取消订单")
    @RequestMapping(value = "/cancel/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult cancelOrder(@PathVariable Long id) {
        return this.orderService.cancelOrder(SecurityUtils.getLoginUser().getUser(), id);
    }

    @ApiOperation("拆单")
    @RequestMapping(value = "/spilt", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult spilt(@RequestBody ExtOrder order) {
        order.setRole(ConstantsUtil.ROLE_CUSTOMER);
        return orderService.spiltOrder(SecurityUtils.getLoginUser().getUser(), order);
    }
    @ApiOperation("获取订单详情:订单信息、操作记录")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult orderDetail(@PathVariable Long id) {
        ExtOrderDetail orderDetailResult = this.orderService.orderDetail(id);

        Long configLogisticsCompanyId = orderDetailResult.getConfigLogisticsCompanyId();
        ConfigLogisticsCompany configLogisticsCompany = configLogisticsCompanyService.selectConfigLogisticsCompanyById(configLogisticsCompanyId);

        if(null != configLogisticsCompany) {
            orderDetailResult.setConfigLogisticsCompanyName(configLogisticsCompany.getCompanyName());
        }

        if(null == orderDetailResult.getStorageTimeBegin()) {
            orderDetailResult.setStorageTimeSize(0L);
        } else {
            Date date = new Date();
            Instant now = date.toInstant();

            Instant end = orderDetailResult.getStorageTimeBegin().toInstant();
            Long day = ChronoUnit.DAYS.between(end, now);
            if(day >0) {
                orderDetailResult.setStorageTimeSize(day);
            }else {
                orderDetailResult.setStorageTimeSize(0L);
            }
        }


        //获取当前订单花费的日元总
        QueryWrapper<CustomerBill> q = new QueryWrapper<>();
        List<String> types = new ArrayList<>();
        types.add("2");
        types.add("3");
        types.add("7");
        types.add("10");
        types.add("11");
        types.add("12");

        Long userId = SecurityUtils.getUserId();

        q.in("type_detail" , types);
        q.eq("user_id" , userId);
        q.eq("order_no" , id);
        q.eq("del_flag" , 0);

        List<CustomerBill> customerBills = customerBillMapper.selectList(q);

        BigDecimal moneyJp = new BigDecimal(0);
        for(CustomerBill s : customerBills) {
            BigDecimal moneyJp1 = s.getMoneyJp();
            if (null != moneyJp1) {
                moneyJp = moneyJp.add(moneyJp1);
            }
        };

        if(BigDecimal.ZERO.compareTo(moneyJp) == 0) {
            moneyJp = orderDetailResult.getTotalPrice().multiply(orderDetailResult.getRate());
        }



        orderDetailResult.setMoneyJp(moneyJp);

        //获得美元汇率
        ExchangeRate exchangeRate = exchangeRateService.queryUsdExchangeRate();
        BigDecimal moneyUSD = BigDecimal.ZERO;
        for(CustomerBill s : customerBills) {
            BigDecimal money = s.getMoney();
            if (null != money) {
                moneyUSD = moneyUSD.add(money.multiply(exchangeRate.getExchangeRate()).setScale(2,BigDecimal.ROUND_UP));
            }
        };

        if(BigDecimal.ZERO.compareTo(moneyUSD) == 0) {
            moneyUSD = orderDetailResult.getTotalPrice().multiply(exchangeRate.getExchangeRate().setScale(2,BigDecimal.ROUND_UP));
        }
        orderDetailResult.setMoneyUSD(moneyUSD);
        return AjaxResult.success(orderDetailResult);
    }

    @ApiOperation("修改订单信息")
    @RequestMapping(value = "/updateOrderInfo", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult updateOrderInfo(@RequestBody OrderInfoUpdateParam orderInfoUpdateParam) {
        return this.orderService.updateOrderInfo(orderInfoUpdateParam);
    }

    @ApiOperation("获取账单详情:账单信息、账单明细，参数为订单id")
    @RequestMapping(value = "/payment/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult paymentDetail(@PathVariable String id) {
        ExtPaymentDetail paymentDetailResult = this.orderService.paymentDetail(id);
        return AjaxResult.success(paymentDetailResult);
    }

    @ApiOperation("上传")
    @RequestMapping("/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(HttpServletRequest request, HttpServletResponse response, ExtUploadFileDto upfile) {
        try {
            if(upfile==null){
                return AjaxResult.error(10143);
            }else{
                String fileName = upfile.getFile().getOriginalFilename();
                String extraName = fileName.substring(fileName.lastIndexOf("."));
                InputStream inputStream = upfile.getFile().getInputStream();
                SecureRandom random = new SecureRandom();
                String imageName = "oss_" + System.currentTimeMillis() + "_" + random.nextInt(10000) + extraName;
                //上传oss
                return AliOssUploadUtils.uploadOss(imageName,inputStream);
            }
        } catch (IOException e) {
            return AjaxResult.error(ResponseCode.UPLOAD_FAIL);
        }
    }

    @ApiOperation("查询检品列表")
    @RequestMapping(value = "/getNameList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getNameList(HttpServletRequest request, ExtName extName) {
        //TODO 更换检品
        String headerLanguage = request.getHeader("Accept-Language");
        extName.setHeaderLanguage(headerLanguage);
        return null;
    }

    @ApiOperation("创建订单")
    @RequestMapping(value = "/create", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public AjaxResult create(@RequestBody ExtCreateOrder extOrder) {

/*        List<ExtCreateOrderDetail> detailList = extOrder.getDetailList();

        String errorMsg = "";
        detailList.forEach(
                s -> {
                   if("0".equals(s.getOrderType())) {
                        if(StringUtils.isBlank(s.getFnsku())) {
                        }
                   }
                   if("2".equals(s.getOrderType())) {
                   }
                   if("3".equals(s.getOrderType())) {
                   }
                   if("4".equals(s.getOrderType())) {
                   }
                }
        );*/


        //后台获取汇率
        com.alibaba.fastjson2.JSONObject latestRate = exchangeRateService.getRate();
        BigDecimal rate = (BigDecimal)latestRate.get("rate");

        if(null != extOrder.getRate()) {
            if(rate.compareTo(extOrder.getRate()) != 0) {
                return AjaxResult.error(MessageUtils.getMessage(10308));
            }
        }

        return orderService.createOrder(extOrder);
    }

    @ApiOperation("获取商品信息")
    @RequestMapping(value = "/getGoodsInfo", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getGoodsInfo(String url) {
        return TaobaoUtil.getGoodsInfo(url);
    }

    /**
     * 执行导入
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "importAction", produces = "application/json;charset=UTF-8")
    public AjaxResult importAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return  this.orderService.uploadFile(request, response);
    }

    /**
     * 下载导入模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "downloadTemplateAction", method = RequestMethod.GET)
    public void downloadTemplateAction(HttpServletRequest request, HttpServletResponse response) {

        String templatePath = GlobalProperties.orderTemplate;
        System.out.println(templatePath+"==================================================");
        if (StringUtils.isNotBlank(templatePath)) {
            File f = new File(templatePath);
            if (f.exists()) {
                downloadFile(request, f, response, false);
            }
        }
    }

    /**
     * 下载文件
     *
     * @param file
     * @param response
     * @param isDelete
     */
    private void downloadFile(HttpServletRequest request, File file, HttpServletResponse response, boolean isDelete) {
        // 清空response
        response.reset();
        try (
                InputStream in = new FileInputStream(file);
                OutputStream out = response.getOutputStream();
        ) {
            String fileName = file.getName();
            response.reset();
            response.setHeader("content-disposition", "attachment;filename=" + new String((fileName).getBytes("UTF-8"), "ISO8859-1"));
            String userAgent = request.getHeader("user-agent");
            if (userAgent != null && userAgent.indexOf("Edge") >= 0) {
                fileName = URLEncoder.encode(fileName, "UTF8");
            } else if (userAgent != null &&(userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0
                    || userAgent.indexOf("Safari") >= 0)) {
                fileName = new String((fileName).getBytes("UTF-8"), "ISO8859-1");
            } else {
                //其他浏览器V
                fileName = URLEncoder.encode(fileName, "UTF8");
            }
            // 以流的形式下载文件。
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            //写文件
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            if (isDelete) {
                if(file.delete()){
                    log.info("do something...");
                }
            }
        } catch (IOException e) {
            log.info(ConstantsUtil.EXCEPTION_CONTEXT,e);
        }
    }

    @ApiOperation("申请发货")
    @RequestMapping(value = "/applySendOrder", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult applySendOrder(@RequestBody ExtApplyOrder order) {
        return orderService.applySendOrder(order);
    }

    @ApiOperation("获取可申请发货数量")
    @RequestMapping(value = "/getCanApplyCount", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getCanApplyCount(@RequestParam("id") Long id) {
        return orderService.getCanApplyCount(id);
    }




    @ApiOperation("/修改出库方式")
    @GetMapping("/updateOutbound")
    public AjaxResult updateOutbound(OutboundReq req) {

        if(StringUtils.isBlank(req.getOrderType()) || null == req.getOrderId()) {
            AjaxResult.success();
        }

        QueryWrapper<Order> qO = new QueryWrapper<>();
        qO.eq("id" , req.getOrderId());
        Order order = orderMapper.selectOne(qO);
        order.setOrderType(req.getOrderType());
        orderMapper.updateById(order);

        QueryWrapper<OrderDetail> qD = new QueryWrapper<>();
        qD.eq("order_id" , req.getOrderId());
        OrderDetail orderDetail = orderDetailMapper.selectOne(qD);
        if(StringUtils.isNotBlank(req.getFnsku())) {
            orderDetail.setFnsku(req.getFnsku());
        }
        if(StringUtils.isNotBlank(req.getAsin())) {
            orderDetail.setAsin(req.getAsin());
        }
        if(StringUtils.isNotBlank(req.getGoodsNameCus())) {
            orderDetail.setGoodsNameCus(req.getGoodsNameCus());
        }
        orderDetailMapper.updateById(orderDetail);

        return AjaxResult.success();
    }




    @ApiOperation("/修改地址")
    @GetMapping("/updateAddress")
    public AjaxResult updateAddress(AddressReq req) {

        if( null == req.getOrderId()) {
            AjaxResult.success();
        }

        QueryWrapper<OrderDetail> qD = new QueryWrapper<>();
        qD.eq("order_id" , req.getOrderId());
        OrderDetail orderDetail = orderDetailMapper.selectOne(qD);

        if(StringUtils.isNotBlank(req.getReceiver())) {
            orderDetail.setReceiver(req.getReceiver());
        }

        if(StringUtils.isNotBlank(req.getReceiverAddress())) {
            orderDetail.setReceiverAddress(req.getReceiverAddress());
        }

        if(StringUtils.isNotBlank(req.getReceiverEmail())) {
            orderDetail.setReceiverEmail(req.getReceiverEmail());
        }

        if(StringUtils.isNotBlank(req.getReceiverPhone())) {
            orderDetail.setReceiverPhone(req.getReceiverPhone());
        }

        if(StringUtils.isNotBlank(req.getReceiverZipCode())) {
            orderDetail.setZipCode(req.getReceiverZipCode());
        }

        orderDetailMapper.updateById(orderDetail);
        return AjaxResult.success();
    }




    @ApiOperation("/修改物流")
    @GetMapping("/updateLogistics")
    public AjaxResult updateAddress(Long configLogisticsCompanyId , Long orderId) {
        QueryWrapper<OrderDetail> qD = new QueryWrapper<>();
        qD.eq("order_id" , orderId);
        OrderDetail orderDetail = orderDetailMapper.selectOne(qD);
        orderDetail.setConfigLogisticsCompanyId(configLogisticsCompanyId);
        orderDetailMapper.updateById(orderDetail);
        return AjaxResult.success();

    }



    @ApiOperation("/获取系统免仓储费时间")
    @GetMapping("/getStorageTime")
    public AjaxResult getStorageTime() {


        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_label" , "sys_storage_time_d");
        queryWrapper.eq("status" , 0);
        queryWrapper.last(" limit 1 ");
        SysDictData sysDictData = sysDictDataMapper.selectOne(queryWrapper);

        Integer time = 60;

        if(null != sysDictData &&  null != sysDictData.getDictValue()) {
            time = Integer.valueOf(sysDictData.getDictValue());
        }

        return AjaxResult.success(time);
    }

    @ApiOperation("导出仓储订单")
    @GetMapping("exportWarehouseOrderList")
    public void exportWarehouseOrderList(HttpServletRequest request,HttpServletResponse response,OrderQueryParam queryParam) throws Exception{

        if(StringUtils.isNotBlank(queryParam.getOrderNo())) {
            if(queryParam.getOrderNo().contains("-")) {
                queryParam.setOrderShowNo(queryParam.getOrderNo());
            } else {
                queryParam.setId(Long.valueOf(queryParam.getOrderNo()));
            }
        }

        queryParam.setCustomerUserId(SecurityUtils.getUserId());
        List<ExtOrder> list = this.orderService.list(queryParam);
        List<ExtOrder> list_new = new ArrayList<>();

        Date date = new Date();
        Instant now = date.toInstant();

        list.forEach(
                s -> {

                    if(com.pulaien.common.utils.StringUtils.isNotEmpty(s.getGoodsSpecs())) {
                        String[] split = s.getGoodsSpecs().split(";");
                        s.setGoodsSpecsList(Arrays.stream(split).collect(Collectors.toList()));
                        s.setStorageTimeSize(0L);
                        if(null != s.getStorageTimeBegin()) {
                            Instant end = s.getStorageTimeBegin().toInstant();
                            Long day = ChronoUnit.DAYS.between(end, now);
                            if(day >0) {
                                s.setStorageTimeSize(day);
                            }
                        }



                        list_new.add(s);
                    }
                }
        );

        Map<String, Object> map = new HashMap<String, Object>();
        ClassPathResource classPathResource = null;

        //根据不同语言对应不同模板
        String acceptLanguage = request.getHeader("Accept-Language");
        if ("zh-cn".equals(acceptLanguage)){
            classPathResource = new ClassPathResource("excelTemplates" + File.separator + "warehouseOrderTemplateZh.xlsx");
            for (ExtOrder extOrder : list_new) {
                //处理订单状态名称
                if (extOrder.getOrderStatus().equals(ConstantsUtil.ORDER_STATUS_16)){
                    extOrder.setOrderStatusName("仓库保管");
                }
                //处理图片
                if (StringUtils.isNotBlank(extOrder.getPictureUrl())) {
                    if (extOrder.getPictureUrl().startsWith("//")){
                        extOrder.setPictureUrl("https:" + extOrder.getPictureUrl());
                    }
                    ImageEntity imageEntity = new ImageEntity();
                    imageEntity.setUrl(extOrder.getPictureUrl());
                    extOrder.setImgEntity(imageEntity);
                } else {
                    extOrder.setImgEntity(new ImageEntity());
                }
                //处理创建时间
                extOrder.setOrderTime(DateUtils.DateToString(new Date(Long.valueOf(extOrder.getCreateTime())*1000), EnumDateStyle.YYYY_MM_DD_HH_MM_SS));
            }
        }else if ("ja-ja".equals(acceptLanguage)){
            classPathResource = new ClassPathResource("excelTemplates" + File.separator + "warehouseOrderTemplateJa.xlsx");
            for (ExtOrder extOrder : list_new) {
                //处理订单状态名称
                if (extOrder.getOrderStatus().equals(ConstantsUtil.ORDER_STATUS_16)){
                    extOrder.setOrderStatusName("倉庫保管");
                }
                //处理图片
                if (org.apache.commons.lang3.StringUtils.isNotBlank(extOrder.getPictureUrl())) {
                    if (extOrder.getPictureUrl().startsWith("//")){
                        extOrder.setPictureUrl("https:" + extOrder.getPictureUrl());
                    }
                    ImageEntity imageEntity = new ImageEntity();
                    imageEntity.setUrl(extOrder.getPictureUrl());
                    extOrder.setImgEntity(imageEntity);
                } else {
                    extOrder.setImgEntity(new ImageEntity());
                }
                //处理创建时间
                extOrder.setOrderTime(DateUtils.DateToString(new Date(Long.valueOf(extOrder.getCreateTime())*1000), EnumDateStyle.YYYY_MM_DD_HH_MM_SS));
            }
        }else {
            classPathResource = new ClassPathResource("excelTemplates" + File.separator + "warehouseOrderTemplateEn.xlsx");
            for (ExtOrder extOrder : list_new) {
                //处理订单状态名称
                if (extOrder.getOrderStatus().equals(ConstantsUtil.ORDER_STATUS_16)){
                    extOrder.setOrderStatusName("In storage");
                }
                //处理图片
                if (org.apache.commons.lang3.StringUtils.isNotBlank(extOrder.getPictureUrl())) {
                    if (extOrder.getPictureUrl().startsWith("//")){
                        extOrder.setPictureUrl("https:" + extOrder.getPictureUrl());
                    }
                    ImageEntity imageEntity = new ImageEntity();
                    imageEntity.setUrl(extOrder.getPictureUrl());
                    extOrder.setImgEntity(imageEntity);
                } else {
                    extOrder.setImgEntity(new ImageEntity());
                }
                //处理创建时间
                extOrder.setOrderTime(DateUtils.DateToString(new Date(Long.valueOf(extOrder.getCreateTime())*1000), EnumDateStyle.YYYY_MM_DD_HH_MM_SS));
            }
        }


        TemplateExportParams template = new TemplateExportParams(classPathResource.getPath(),true);
        map.put("orderList",list_new);
        Workbook workbook = ExcelExportUtil.exportExcel(template, map);

//        File saveFolder = new File("D:/home/excel/");
//        if (!saveFolder.exists()) {
//            boolean mkdirs = saveFolder.mkdirs();
//        }

        ExcelUtils.workbookExportExcel(workbook,response,"仓储订单.xlsx");

    }

    @ApiOperation("订单列表订单状态/数量/百分比")
    @RequestMapping(value = "/allOrderCount",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult allOrderCount(){
        OrderQueryParam queryParam = new OrderQueryParam();
        queryParam.setCustomerUserId(SecurityUtils.getUserId());
        List<Map<String, Object>> result = orderService.allOrderCount(queryParam);
        return AjaxResult.success(result);
    }


}
